<template>
  <el-card class="w-full pt-[5px] pb0">
    <CheckType
      v-model="searchForm.checkstatusByGroup"
      @typeChange="handleSearch"
      :countMap="countMap"
    />
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="合同编号" prop="code">
            <el-input v-model="searchForm.code" placeholder="合同编号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="合同名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同类别" prop="projectTypeCode">
            <CustomTreeSelect
              placeholder="合同类别"
              v-model="searchForm.projectTypeCode"
              valueKey="id"
              labelKey="label"
              :dataList="contractTypeList"
              :isFetch="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="负责人" prop="chargerName">
            <el-input v-model="searchForm.chargerName" placeholder="负责人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0">
            <el-input
              v-model="searchForm.minTotalMoney"
              placeholder="最小项目总经费"
              clearable
              style="width: calc(50% - 10px)"
              @input="fomateNumber(searchForm, 'minTotalMoney', $event)"
            />
            <span style="width: 20px; text-align: center">至</span>
            <el-input
              v-model="searchForm.maxTotalMoney"
              placeholder="最大项目总经费"
              clearable
              style="width: calc(50% - 10px)"
              @input="fomateNumber(searchForm, 'maxTotalMoney', $event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="签定日期">
            <el-date-picker
              v-model="searchForm.startAuthorizeDate"
              type="year"
              style="width: calc(50% - 10px)"
            />
            <span style="width: 20px; text-align: center">至</span>
            <el-date-picker
              v-model="searchForm.endAuthorizeDate"
              type="year"
              style="width: calc(50% - 10px)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitId">
            <CustomTreeSelect
              placeholder="所属单位"
              v-model="searchForm.unitId"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :isFetch="false"
              :dataList="unitList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人电话" prop="chargerPhone">
            <el-input v-model="searchForm.chargerPhone" placeholder="负责人电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人邮箱" prop="chargerEmail">
            <el-input v-model="searchForm.chargerEmail" placeholder="负责人邮箱" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同有效状态" prop="validState">
            <CustomTreeSelect
              placeholder="合同有效状态"
              v-model="searchForm.validState"
              paramsName="进账合同有效状态"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="进行状态" prop="projectStatusId">
            <CustomTreeSelect
              paramsName="项目状态"
              placeholder="进行状态"
              v-model="searchForm.projectStatusId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方名称" prop="buyerName">
            <el-input v-model="searchForm.buyerName" placeholder="甲方名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方联系人" prop="buyerChargerName">
            <el-input v-model="searchForm.buyerChargerName" placeholder="甲方联系人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方联系电话" prop="buyerTel">
            <el-input v-model="searchForm.buyerTel" placeholder="甲方联系电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同成员" prop="members">
            <el-input v-model="searchForm.members" placeholder="合同成员" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" prop="checkstatus">
            <CustomTreeSelect
              placeholder="审核状态"
              v-model="searchForm.checkstatus"
              valueKey="dictValue"
              labelKey="dictLabel"
              :isFetch="false"
              :dataList="checkStatusList"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button type="primary" @click="handleAdd" v-if="verifyRoleType.isKyryOrkycgly()">
        <el-icon class="mr-[5px]"><Plus /></el-icon>
        新增
      </el-button>
      <template v-if="verifyRoleType.isKymsOrkycgly()">
        <el-button @click="handleDelSelect">
          <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
          删除
        </el-button>
        <el-button @click="handleExport">
          <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
        </el-button>
      </template>
    </div>
    <el-table
      :data="tableData"
      class="w-full"
      stripe
      row-key="id"
      v-loading="loading"
      ref="tableRef"
    >
      <el-table-column
        type="selection"
        width="40"
        :selectable="(row) => row.checkStatus != 1 && row.checkStatus != 2"
        v-if="!verifyRoleType.isKyry()"
      />
      <el-table-column prop="code" label="合同编号" width="110" />
      <el-table-column prop="name" label="合同名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.id)">{{ row.proName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="合同类别" width="150">
        <template #default="{ row }">
          <CommonTreeLabel
            :dataList="contractTypeList"
            :value="row.projectTypeCode"
            labelKey="labelLocal"
          />
        </template>
      </el-table-column>
      <el-table-column label="负责人" width="90">
        <template #default="{ row }">
          <el-link
            type="primary"
            @click="handleViewPerson(row.chargerCode)"
            v-if="row.chargerCode"
            >{{ row.chargerName }}</el-link
          >
          <span v-else>{{ row.chargerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="feeAuthorize" label="合同经费（万元）" width="95"/>
      <el-table-column prop="feeIn" label="到账金额（万元）" width="95"/>
      <el-table-column prop="authorizeDate" label="签订日期" width="100"/>
      <el-table-column prop="unitName" label="所属单位" width="120"/>
      <el-table-column label="审核状态" width="100">
        <template #default="{ row }">
          <CommonLabel
            :dataList="checkStatusList"
            valueKey="dictValue"
            labelKey="dictLabel"
            :value="row.checkStatus"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="{ row }">
          <!-- <el-button type="primary" size="small" plain @click="handleTodo(row.id)"
            >办理业务</el-button
          > -->
          <template v-if="row.projectStatusId == '0'">
            <template v-if="[-1, 3].includes(Number(row.checkStatus))">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleEdit(row.id, row.isAuditor, row.taskId, row.checkStatus)"
              >
                编辑
              </el-button>
              <el-button type="danger" size="small" plain @click="handleDel(row.id)"
                >删除</el-button
              >
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleDocument(row.id, row.isAuditor, row.taskId, row.checkStatus)"
                >文档+</el-button
              >
            </template>
            <!-- 科研人员 -->
            <template v-if="verifyRoleType.isKyry()">
              <el-button
                type="warning"
                size="small"
                plain
                @click="handleCancel(row.processInstanceId, row.id)"
                v-if="Number(row.checkStatus) == 1 && userId == row.chargerCode"
                :loading="cancelLoading && cancelId == row.id"
                >撤销</el-button
              >
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleTodo(row.id)"
                v-if="Number(row.checkStatus) == 2 && userId == row.chargerCode"
                >办理业务</el-button
              >
            </template>
            <!-- 科研秘书或者科研管理员 -->
            <template v-if="verifyRoleType.isKymsOrkycgly()">
              <template v-if="Number(row.checkStatus) == 1">
                <el-button
                  type="primary"
                  size="small"
                  plain
                  @click="handleEdit(row.id, row.isAuditor, row.taskId, row.checkStatus)"
                >
                  编辑
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  plain
                  @click="handleCheck(row.id, row.processInstanceId)"
                  v-if="row.isAuditor"
                  >审核</el-button
                >
              </template>
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleDocument(row.id, row.isAuditor, row.taskId, row.checkStatus)"
                v-if="Number(row.checkStatus) == 2"
                >文档+</el-button
              >
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <AddModal ref="addModalRef" @add-success="handleSearch" v-if="addModalVisible" />
  <ViewModal ref="viewModalRef" v-if="viewModalVisible" />
  <EditModal ref="editModalRef" @edit-success="handleSearch" v-if="editModalVisible" />
  <DocumentModal ref="documentModalRef" v-if="documentModalVisible" />
  <CheckModal ref="checkModalRef" v-if="checkModalVisible" @check-success="handleSearch" />
  <TodoModal ref="todoModalRef" />
  <PersonView ref="personViewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="exportFieldList"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import CheckType from "@/views/project/components/CheckType.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import AddModal from "./components/AddModal.vue";
import EditModal from "./components/EditModal.vue";
import ViewModal from "./components/ViewModal.vue";
import DocumentModal from "./components/DocumentModal.vue";
import CheckModal from "./components/CheckModal.vue";
import TodoModal from "@/views/project/components/TodoModal.vue";
import exportModal from "@/components/export";
import PersonView from "@/views/project/components/PersonView.vue";
import { getList, delRecords, exportRecords, getCount } from "@/api/project/zx/lxxm";
import { cancelProcess, exportFields } from "@/api/project/common";
import { ElMessageBox, ElMessage } from "element-plus";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { verifyRoleType, downloadFile, fomateNumber } from "@/utils/main";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const userId = userStore.userRealId;
const unitList = useCommonFetch("成果归属单位");
const contractTypeList = useCommonFetch("项目分类（横向）");
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const searchFormOpen = ref(false);
const addModalRef = ref();
const addModalVisible = ref(false);
const editModalRef = ref();
const editModalVisible = ref(false);
const viewModalRef = ref();
const viewModalVisible = ref(false);
const documentModalRef = ref();
const documentModalVisible = ref(false);
const checkModalRef = ref();
const checkModalVisible = ref(false);
const todoModalRef = ref();
const searchFormRef = ref();
const tableRef = ref();
const personViewModalRef = ref();
const exportFieldList = ref([]);
const exportVisible = ref(false);
const exportTitle = "进账合同签订";
const cancelLoading = ref(false);
const cancelId = ref(null);
const countMap = ref({
  total: 0,
  1: 0,
  2: 0,
  3: 0,
});
const searchForm = ref({
  proClass: "yfContract",
  checkstatusByGroup: "",
  code: "",
  name: "",
  projectTypeCode: [], //合同类别
  chargerName: "", //负责人
  minTotalMoney: "", //最小项目经费
  maxTotalMoney: "", //最大项目经费
  startAuthorizeDate: "", //签订开始日期
  endAuthorizeDate: "", //签订结束日期
  unitId: [], //所属单位
  chargerPhone: "", //负责人电话
  chargerEmail: "", //负责人邮箱
  validState: [], //合同有效状态
  projectStatusId: [], //进行状态
  buyerName: "", //甲方名称
  buyerChargerName: "", //甲方联系人
  buyerTel: "", //甲方联系电话
  members: "", //合同成员
  checkstatus: [], //审核状态
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNo: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
        projectTypeCode: searchForm.value.projectTypeCode.join(","),
        unitId: searchForm.value.unitId.join(","),
        validState: searchForm.value.validState.join(","),
        projectStatusId: searchForm.value.projectStatusId.join(","),
        checkstatus: searchForm.value.checkstatus.join(","),
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击新增
const handleAdd = () => {
  addModalVisible.value = true;
  nextTick(() => {
    addModalRef.value.add();
  });
};
//点击编辑
const handleEdit = (id, isAuditor, taskId, checkStatus) => {
  editModalVisible.value = true;
  nextTick(() => {
    editModalRef.value.edit(id, isAuditor, taskId, checkStatus);
  });
};
//文件文档+
const handleDocument = (id, isAuditor, taskId, checkStatus) => {
  documentModalVisible.value = true;
  nextTick(() => {
    documentModalRef.value.edit(id, isAuditor, taskId, checkStatus);
  });
};
//审核
const handleCheck = (id, processId) => {
  checkModalVisible.value = true;
  nextTick(() => {
    checkModalRef.value.check(id, processId);
  });
};
//点击撤销
const handleCancel = (processId, cId) => {
  cancelId.value = cId;
  ElMessageBox.confirm("撤销后，该审批流程将自动结束，是否确认取消？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      cancelLoading.value = true;
      const res = await cancelProcess(processId);
      if (res.data) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        handleSearch();
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error",
        });
      }
    } catch (error) {
      console.log(error);
    } finally {
      cancelLoading.value = false;
    }
  });
};
//办理业务
const handleTodo = (id) => {
  todoModalRef.value.todo(id);
};
//点击删除
const handleDel = (id) => {
  const params = {
    proId: id,
  };
  handleDelete(delRecords, params);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  const params = {
    proId: ids.join(","),
  };
  handleDelete(delRecords, params);
};
//点击名称
const handleShow = (id) => {
  viewModalVisible.value = true;
  nextTick(() => {
    viewModalRef.value.view(id);
  });
};
//点击人员姓名
const handleViewPerson = (id) => {
  personViewModalRef.value.view(id);
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      exportType: "init",
      proClass: "yfContract",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      const defaultCheckedList = [
        "codeHt",
        "proNameHt",
        "chargerName",
        "feeAuthorizeHt",
        "projectTypeNameHt",
        "authorizeDateHt",
        "unitName",
        "memberNameList",
      ];
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: defaultCheckedList.includes(item.field) ? true : false,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  //exportFieldList为空时才获取数据
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      projectTypeCode: searchForm.value.projectTypeCode.join(","),
      unitId: searchForm.value.unitId.join(","),
      validState: searchForm.value.validState.join(","),
      projectStatusId: searchForm.value.projectStatusId.join(","),
      checkstatus: searchForm.value.checkstatus.join(","),
      exportStr: cols.join(","),
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    } else {
      ElMessage({
        message: "导出失败！",
        type: "error",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
    projectTypeCode: searchForm.value.projectTypeCode.join(","),
    unitId: searchForm.value.unitId.join(","),
    validState: searchForm.value.validState.join(","),
    projectStatusId: searchForm.value.projectStatusId.join(","),
    checkstatus: searchForm.value.checkstatus.join(","),
    checkstatusByGroup: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      1: 0,
      2: 0,
      3: 0,
    };
    if (res.data) {
      let totalCount = 0;
      res.data.forEach((item) => {
        countMap.value[item.classValue] = item.classCount;
        totalCount += Number(item.classCount);
      });
      countMap.value.total = totalCount;
    }
  } catch (error) {
    console.log(error);
  }
}
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.minTotalMoney = "";
  searchForm.value.maxTotalMoney = "";
  searchForm.value.startAuthorizeDate = "";
  searchForm.value.endAuthorizeDate = "";
  handleSearch();
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
